import dotenv from 'dotenv'
import { createBot, createProvider, createFlow, addKeyword } from '@builderbot/bot'
import { MysqlAdapter as Database } from '@builderbot/database-mysql'
import { BaileysProvider as Provider } from '@builderbot/provider-baileys'
import {getDifyReply} from "./dify/index.js";

const PORT = process.env.PORT ?? 3008

const flow = addKeyword([])
.addAction(async (msg, { flowDynamic }) => {
	const reply = await getDifyReply(msg.body, msg.from)
	console.log('🌸🌸🌸 / msg: ',msg)
    return await flowDynamic(reply)
})

const main = async () => {
    const adapterFlow = createFlow([flow])

    const adapterProvider = createProvider(Provider)

	const env = dotenv.config().parsed // 环境参数
    const adapterDB = new Database({
        host: env.MYSQL_DB_HOST,
        user: env.MYSQL_DB_USER,
        database: env.MYSQL_DB_NAME,
        password: env.MYSQL_DB_PASSWORD,
    })

    const { handleCtx,httpServer } = await createBot({
        flow: adapterFlow,
        provider: adapterProvider,
        database: adapterDB,
    })

	adapterProvider.server.post(
        '/v1/messages',
        handleCtx(async (bot, req, res) => {
            await bot.sendMessage('+8618053198119', 'ping')
            return res.end('pong')
        })
    )

    /*

    adapterProvider.server.post(
        '/v1/register',
        handleCtx(async (bot, req, res) => {
            const { number, name } = req.body
            await bot.dispatch('REGISTER_FLOW', { from: number, name })
            return res.end('trigger')
        })
    )

    adapterProvider.server.post(
        '/v1/samples',
        handleCtx(async (bot, req, res) => {
            const { number, name } = req.body
            await bot.dispatch('SAMPLES', { from: number, name })
            return res.end('trigger')
        })
    )

    adapterProvider.server.post(
        '/v1/blacklist',
        handleCtx(async (bot, req, res) => {
            const { number, intent } = req.body
            if (intent === 'remove') bot.blacklist.remove(number)
            if (intent === 'add') bot.blacklist.add(number)

            res.writeHead(200, { 'Content-Type': 'application/json' })
            return res.end(JSON.stringify({ status: 'ok', number, intent }))
        })
    )*/

    httpServer(+PORT)
}

main()
